package org.compiere.process;

import java.io.File;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.MessageFormat;
import java.util.Properties;
import java.util.logging.Level;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.CellFormat;
import jxl.format.Colour;
import jxl.format.VerticalAlignment;
import jxl.write.DateFormat;
import jxl.write.DateTime;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableCell;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.adempiere.exceptions.AdempiereException;
import org.compiere.apps.ADialog;
import org.compiere.model.MAttachmentEntry;
import org.compiere.model.MBPartner;
import org.compiere.model.Mhrmabsence;
import org.compiere.model.X_hrm_absence;
import org.compiere.util.Env;
import org.compiere.util.Msg;
import org.eevolution.model.X_HR_Department;
import org.eevolution.model.X_HR_Employee;

import extend.org.compiere.hrm.ExcelCell;
import extend.org.compiere.utils.Util;

public class ReportSickList extends SvrProcess {
	
	/** Current context		*/
	private Properties m_ctx;
	/**	 */
	private ProcessInfo pi;
	/** */
	private int HR_Department_ID = 0;
	/** */
	private int HR_Block_ID = 0;
	/** */
	private String path = "";
	/** */
	X_HR_Department department = null;
	/** */
	X_HR_Department block = null;
	/** */
	Timestamp startDate;
	/** */
	Timestamp endDate;
	/** */
	Mhrmabsence[] hrmabs = null;
	/** */
	MBPartner[] bp = null;

	@Override
	protected void prepare() {

		log.info(" Report Sick List ");
		m_ctx = Env.getCtx();
		pi = getProcessInfo();
		
		ProcessInfoParameter[] para = getParameter();
		for (int i = 0; i < para.length; i++)	{
			String name = para[i].getParameterName();
			if (name == null); 
				//
			else if (name.compareTo("HR_Block_ID") == 0 && para[i].getParameter() != null)
				HR_Block_ID = new BigDecimal(Integer.parseInt(para[i].getParameter().toString())).intValue();
			else if (name.compareTo("HR_Department_ID") == 0 && para[i].getParameter() != null)
				HR_Department_ID = new BigDecimal(Integer.parseInt(para[i].getParameter().toString())).intValue();
			else if (name.toLowerCase().endsWith("directory"))
				path = (String)para[i].getParameter();
			else if (name.compareTo("StartDate") == 0){
				startDate = (Timestamp) para[i].getParameter();
				endDate = (Timestamp) para[i].getParameter_To();
			}
			else
			{
				log.log(Level.INFO, "Unknown Parameter: " + name);
			}
		}
		
		if(path.isEmpty())
			path = Util.localFilePath;
		else
			path = path + System.getProperty("file.separator");

		department = new X_HR_Department(getCtx(), HR_Department_ID, null);
		block = new X_HR_Department(getCtx(), HR_Block_ID, null);
		

	}

	@Override
	protected String doIt() throws Exception {

		// Types of cells for
		Label label;
		Number number;
		DateTime dateCell;
		// There are checks for a specified pattern
		String templateName = "SampleSickList";
		
		//
		MAttachmentEntry entry = Util.getAttachment(pi, m_ctx, templateName);
		if(entry == null)
			throw new AdempiereException(Msg.translate(m_ctx, "NotFoundTemplate")+" "+templateName);
				
		// We define a path to generate
		String fileExtension = entry.getName().substring(entry.getName().lastIndexOf("."),entry.getName().length());
		StringBuffer fullPath = new StringBuffer(path); 
		fullPath.append("Sick list").append(fileExtension);
				
		// 
		File templateCopy = new File(fullPath.toString());
		File temporaryFile = entry.getFile(Util.localFilePath+templateName);
		Workbook tableBook = null;
		WritableWorkbook copy = null;
		WritableSheet sheet = null;
		 try {
			 tableBook = Workbook.getWorkbook(temporaryFile);
			 copy = Workbook.createWorkbook(templateCopy, tableBook);
			 sheet = copy.getSheet(0);
		} catch (Exception e) {
		  	ADialog.error(999, null, "Error tableBook. " + e.getMessage());
		   	return "Error tableBook.";
		}

		ExcelCell cellStart =  Util.getCellStart(tableBook,">>");
		
		// Standart style cell
		WritableCellFormat borderStyle = new WritableCellFormat();
		borderStyle.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
		borderStyle.setAlignment(Alignment.CENTRE);
		borderStyle.setVerticalAlignment(VerticalAlignment.CENTRE);
		borderStyle.setWrap(true);
		// Description style cell
		WritableCellFormat descriptStyle = new WritableCellFormat();
		descriptStyle.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
		descriptStyle.setAlignment(Alignment.LEFT);
		descriptStyle.setVerticalAlignment(VerticalAlignment.CENTRE);
		descriptStyle.setWrap(true);
		// Department style cell
		WritableFont fontDepartment = new WritableFont (WritableFont.TIMES, 12, WritableFont.BOLD);
		WritableCellFormat cellDepartment = new WritableCellFormat(fontDepartment);
		cellDepartment.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
		cellDepartment.setAlignment(Alignment.CENTRE);
		cellDepartment.setVerticalAlignment(VerticalAlignment.CENTRE);
		cellDepartment.setBackground(Colour.TAN);
		// Title style cell
		WritableFont fontTitle = new WritableFont (WritableFont.TIMES, 14, WritableFont.NO_BOLD);
		WritableCellFormat titleStyle = new WritableCellFormat(fontTitle);
		titleStyle.setAlignment(Alignment.CENTRE);
		titleStyle.setVerticalAlignment(VerticalAlignment.CENTRE);
		// Date format Setting
		DateFormat customDateFormat = new DateFormat ("dd.MM.yyyy"); 
		WritableCellFormat dateFormat = new WritableCellFormat (customDateFormat); 
		dateFormat.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
		dateFormat.setAlignment(Alignment.CENTRE);
		dateFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
		
	    // header report
	    WritableCell readCell = sheet.getWritableCell(1, 1);
		CellFormat readFormat = readCell.getCellFormat();
		label = new Label(1, 1, sheet.getCell(1, 1).getContents()+Util.getOrgInfo().getDescription(), readFormat);
		sheet.addCell(label);
		
		// set title
		if(HR_Block_ID != 0)
			label = new Label(1, 2, "Блока "+block.getName(), titleStyle);
		else
			label = new Label(1, 2, "", titleStyle);
		sheet.addCell(label);
		
		Object[] param = new Object[]{Util.getMonthName(new Timestamp(startDate.getTime()), Env.getAD_Language(getCtx()), false), 
									  Integer.toString(new org.joda.time.DateTime(startDate.getTime()).getYear()),
									  Util.getMonthName(new Timestamp(endDate.getTime()), Env.getAD_Language(getCtx()), false),
									  Integer.toString(new org.joda.time.DateTime(endDate.getTime()).getYear())};
		if(new org.joda.time.DateTime(startDate.getTime()).getMonthOfYear() != new org.joda.time.DateTime(endDate.getTime()).getMonthOfYear())
			label = new Label(1, 3, sheet.getCell(1, 3).getContents()+MessageFormat.format(" {0} {1} - {2} {3} года", param), titleStyle);
		else
			label = new Label(1, 3, MessageFormat.format(" за {0} месяц {1} года", param), titleStyle);
		sheet.addCell(label);
		
		X_HR_Employee he = null;
		bp = MBPartner.getEmployees(HR_Block_ID, HR_Department_ID, startDate, endDate);
		int col = cellStart.getC(); // offset by the number of first columns
		int row = cellStart.getR();
		int dId = 0; // Departmnet ID Merge cells
		int dep = 0;
		int num = 1;
		int j = row;
		for(MBPartner b: bp){
			hrmabs = Mhrmabsence.getAbsenceType(b.getC_BPartner_ID(), startDate, endDate, X_hrm_absence.HRM_ABSENCETYPE_Illness);
			for(Mhrmabsence abs: hrmabs){
				
				sheet.setRowView(j+dep, 600);
				// Title
				he = X_HR_Employee.getHR_Employee(b.getC_BPartner_ID(),true); 
				if(dId != he.getHR_Department_ID()){
					dId = he.getHR_Department_ID();
					sheet.insertRow(j+dep);
					sheet.mergeCells(1, j+dep, 6, j+dep);
					sheet.setRowView(j+dep, 500);
					label = new Label(1, j+dep, he.getHR_Department().getName(), cellDepartment); 
					sheet.addCell(label);
					dep++;
				}   
				    
				// #
				number = new Number(col, j+dep, num, borderStyle); 
				sheet.addCell(number);
				// initials
				label = new Label(col+1, j+dep, b.getName(), borderStyle); 
				sheet.addCell(label);
				// Job
				label = new Label(col+2, j+dep, he.getHR_Job().getName(), borderStyle); 
				sheet.addCell(label);
				// Dates
				dateCell = new DateTime(col+3, j+dep, abs.getStartDate(), dateFormat);
				sheet.addCell(dateCell);
				dateCell = new DateTime(col+4, j+dep, abs.getEndDate(), dateFormat);
				sheet.addCell(dateCell);
				// Description
				label = new Label(col+5, j+dep, abs.getDescription(), descriptStyle); 
				sheet.addCell(label);

				num++;
				j++;
			}
		}
		
		if(HR_Block_ID == 0)
			sheet.removeRow(2);
				
		copy.write();
		copy.close();
		tableBook.close();
		temporaryFile.delete();
			       
		// Open the file with the application associated
		String fileName = fullPath.toString();
		Util.launchFile(new File(fileName));
		
		return Msg.translate(m_ctx, "Success");
	}

}
